import { formatIssue, validateMintConfig } from '@mintlify/validation';
import { promises as _promises } from 'fs';
import fse from 'fs-extra';
import { getConfigPath } from '../../utils.js';
const { readFile } = _promises;
export async function updateConfigFile(contentDirectoryPath) {
    const configTargetPath = 'src/_props/mint.json';
    const configPath = await getConfigPath(contentDirectoryPath);
    if (configPath == null) {
        throw Error('Must be run in a directory where a mint.json file exists.');
    }
    let configContents;
    try {
        configContents = await readFile(configPath, 'utf-8');
    }
    catch (err) {
        throw Error(`Unable to read mint.json: ${err}`);
    }
    let configObj;
    try {
        configObj = JSON.parse(configContents);
    }
    catch (err) {
        throw Error(`Unable to parse mint.json: ${err}`);
    }
    const validationResults = validateMintConfig(configObj);
    if (!validationResults.success) {
        const errStr = validationResults.error.issues.map(formatIssue).join('\n');
        throw Error(`Invalid mint.json:\n${errStr}`);
    }
    if (validationResults.warnings.length > 0) {
        console.warn('\nWarnings found in mint.json:');
        validationResults.warnings.forEach((issue) => console.log(formatIssue(issue)));
        console.log();
    }
    try {
        await fse.copy(configPath, configTargetPath, { overwrite: true });
    }
    catch (err) {
        throw Error(`Unable to copy mint.json: ${err}`);
    }
    return validationResults.data;
}
